package com.clkj.tramcarlibrary.fragment.stopDetail;

import android.support.annotation.NonNull;
import android.util.Log;

import com.clkj.tramcarlibrary.entity.StopDetail;
import com.clkj.tramcarlibrary.http.HttpService;
import com.clkj.tramcarlibrary.schedulers.BaseSchedulerProvider;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import rx.Observer;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Administrator on 2017/2/14.
 */

public class StopDetailPresenter implements StopDetailContract.Presenter {

    @NonNull
    StopDetailContract.View mStopDetailView;

    @NonNull
    private final BaseSchedulerProvider mSchedulerProvider;

    @NonNull
    private final HttpService mHttpService;

    @NonNull
    private CompositeSubscription mSubscriptions;

    public StopDetailPresenter(@NonNull StopDetailContract.View mStopDetailView, @NonNull BaseSchedulerProvider mSchedulerProvider, @NonNull HttpService mHttpService) {
        this.mStopDetailView = mStopDetailView;
        this.mSchedulerProvider = mSchedulerProvider;
        this.mHttpService = mHttpService;
        this.mSubscriptions = new CompositeSubscription();

        this.mStopDetailView.setPresenter(this);
    }


    //获取站点的详情
    @Override
    public void getStopDetail(String station_name) {
        mStopDetailView.showLoading();
        Subscription subscription = mHttpService.getStopDetail(station_name)
                .subscribeOn(mSchedulerProvider.computation())
                .observeOn(mSchedulerProvider.ui())
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Log.e("失败", "失败");
                        mStopDetailView.showError("数据获取异常");
                        mStopDetailView.dismissLoading();
                    }

                    @Override
                    public void onNext(JsonObject jsonObject) {
                        Log.e("详情", jsonObject.toString());
                        if (jsonObject.get("status").getAsString().equals("success")) {
                            JsonObject object = jsonObject.get("data").getAsJsonObject();

                            StopDetail stopDetail = new Gson().fromJson(object, StopDetail.class);

                            mStopDetailView.showStopDetail(stopDetail);
                        }
                        else
                        {
                            mStopDetailView.showError("数据获取异常");
                        }
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.unsubscribe();
        mSubscriptions = null;
    }

}
